from django.db.models import Q
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response

from user import models
from utis.jwttool import tool


# Create your views here.
class LoginPwd(APIView):
    def post(self, request):
        account = request.data.get('account', "")
        password = request.data.get('password', "")
        if not account or not password:
            return Response({"code": 400, "msg": "账号或密码不能为空"})
        info = models.User.objects.filter(Q(username=account) | Q(email=account) | Q(phone=account),
                                          isdel=False).first()
        if not info:
            return Response({"code": 400, "msg": "账号不存在"})
        if info.password != password:
            return Response({"code": 400, "msg": "密码错误"})
        token = tool.gettoken({"user": info.id})
        return Response({"code": 200, "msg": "登录成功", "data": {"token": token, "user": info.id}})
